# coding=utf-8

import web

import qrcode
from PIL import Image


urls = (
    '/1u24732j235ab9ek', 'genchannelad'
)
app = web.application(urls, globals())


class genchannelad:

    def GET(self):
        i = web.input()
        print(i)
        base_path = "/www/wwwroot/www.doitedu.cn/tg/static"
        oriad = base_path+"/origin/"+i.oriad
        channel_out = base_path+"/channels/"+i.channel_out
        logo = base_path+"/logo/log-touming.png"
        url = i.url
        ewm_w = int(i.ewm_w)
        ewm_h = int(i.ewm_h)
        loc_x = int(i.loc_x)
        loc_y = int(i.loc_y)
        
        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=2,
        )
        # 添加数据
        qr.add_data(url)
        # 填充数据
        qr.make(fit=True)
        # 生成图片
        img = qr.make_image()
        img = img.convert("CMYK")  # RGBA
        # 添加logo
        icon = Image.open(logo)
        # 获取图片的宽高
        img_w, img_h = img.size
        factor = 6
        size_w = int(img_w / factor)
        size_h = int(img_h / factor)
        icon_w, icon_h = icon.size
        if icon_w > size_w:
            icon_w = size_w
        if icon_h > size_h:
            icon_h = size_h
        # 重新设置logo的尺寸
        icon = icon.resize((icon_w, icon_h), Image.ANTIALIAS)
        w = int((img_w - icon_w) / 2)
        h = int((img_h - icon_h) / 2)
        img.paste(icon, (w, h))

        ewm = img.convert('RGB')
        ewm_small = ewm.resize((ewm_w, ewm_h))  # 将二维码图片调整到合适大小
    
        channel_ad = Image.open(oriad)  # 打开原始广告图片
        channel_ad.paste(ewm_small, (loc_x, loc_y))
    
        channel_ad_rgb = channel_ad.convert('RGB')
        channel_ad_rgb.save(channel_out)
        # close logo
        icon.close()
        channel_ad.close()
        return "0"


if __name__ == "__main__":
    app.run()
